package TCPSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听，等待连接
        //要求本机没有其他服务在监听9999端口
        //注:ServerSocket可以通过accept()返回多个Socket对象[多个客户端连接服务器的并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端，在9999端口监听，等待连接...");
        //2.当没有客户端连接9999端口的时候，程序会阻塞，等待连接
        //  如果有客服端连接，则会被接收，程序继续
        Socket socket = serverSocket.accept();
        //3.通过socket.getInputStream() 读取客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        byte buf[] = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLen));
        }

        //4.回复hello,client
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,client".getBytes());
        socket.shutdownOutput();

        //5.关闭对应的流和socket
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();

    }
}
